package com.hmdp.inteceptor;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.PAGE_VIEW_KEY;
import static com.hmdp.utils.RedisConstants.UNIQUE_VISITOR_KEY;

/**
 * 功能：
 * 作者：4204001140
 * 日期：2024/8/26 22:08
 */
@Slf4j
public class LoginInteceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    public LoginInteceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        HttpSession session = request.getSession();
//        Object user = session.getAttribute("user");
        String token = request.getHeader("authorization");
        Map userMap = redisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        if (userMap.isEmpty()) {
            response.setStatus(401);
            return false;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        UserHolder.saveUser( userDTO);
        redisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY + token, userMap);
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        countUV(userDTO.getId());
        countPV(request);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        UserHolder.removeUser();

    }

    /**
     * 统计独立访客
     */
    public void countUV(Long userId){
        redisTemplate.opsForHyperLogLog().add(UNIQUE_VISITOR_KEY, userId);
        log.info("当前独立访客量：{}", redisTemplate.opsForHyperLogLog().size(UNIQUE_VISITOR_KEY));
    }


    /**
     * 统计页面访问量
     */
    public void countPV(HttpServletRequest request){
        // 获取当前页面路径
        // 对当前页面路径进行统计
        // 获取key对应的数值
        Object pvObj = redisTemplate.opsForValue().get(PAGE_VIEW_KEY );
        if (pvObj == null){
            redisTemplate.opsForValue().set(PAGE_VIEW_KEY, 1L);
        }else{
            Long count = Long.valueOf(pvObj.toString());
            redisTemplate.opsForValue().set(PAGE_VIEW_KEY, count+1);
        }
        log.info("当前页面访问量：{}", redisTemplate.opsForValue().get(PAGE_VIEW_KEY));
    }
}
